import React, { useEffect, useReducer, useCallback } from 'react';
import { Table, message } from 'antd';

const useAsyncTable = (props) => {
  const { owncolumns, queryAction, params, baseProps } = props;
  // 分页数据
  const paginationInitial = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  // table组件全量数据
  const initialState = {
    loading: false,
    pagination: paginationInitial,
    dataSource: [],
  };
  const reducer = (state, action) => {
    const { payload } = action;
    switch (action.type) {
      case 'TOGGLE_LOADING':
        return { ...state, loading: !state.loading };
      case 'SET_PAGINATION':
        return { ...state, pagination: payload.pagination };
      case 'SET_DATA_SOURCE':
        return { ...state, dataSource: payload.dataSource };
      default:
        return state;
    }
  };
  const [state, dispatch] = useReducer(reducer, initialState);

  // 改变页码
  function handleTableChange(payload) {
    if (payload) {
      const { current, pageSize } = payload;
      dispatch({
        type: 'SET_PAGINATION',
        payload: {
          pagination: {
            ...state.pagination,
            current,
            pageSize,
          },
        },
      });
    }
  }
  // useCallback包装请求，缓存依赖，优化组件性能
  const fetchDataWarp = useCallback(fetchData, [
    params,
    state.pagination.current,
    state.pagination.pageSize,
    // owncolumns,
    // queryAction,
  ]);
  async function fetchData() {
    dispatch({
      type: 'TOGGLE_LOADING',
    });
    // 分页字段名称转换
    const { current, pageSize } = state.pagination;
    let res = await queryAction({ current, pageSize, ...params }).catch(
      (err) => {
        dispatch({ type: 'TOGGLE_LOADING' });
        return {};
      },
    );
    // 关闭loading
    dispatch({
      type: 'TOGGLE_LOADING',
    });
    if (res.code === 1) {
      const { total, data } = res;
      dispatch({
        type: 'SET_PAGINATION',
        payload: {
          pagination: { ...state.pagination, total },
        },
      });
      // 回填list数据
      dispatch({
        type: 'SET_DATA_SOURCE',
        payload: {
          dataSource: data,
        },
      });
    } else {
      message.error(res.msg);
    }
  }
  useEffect(() => {
    fetchDataWarp();
  }, [fetchDataWarp]);
  return (
    <Table
      columns={owncolumns(fetchData)}
      pagination={{
        /* 默认分页配置 */
        ...{
          pageSizeOptions: [10, 20, 50, 100],
          showSizeChanger: true,
          locale: {
            items_per_page: '/页',
            jump_to: '跳至',
            page: '页',
          },
        },
        ...state.pagination,
      }}
      dataSource={state.dataSource}
      loading={state.loading}
      onChange={handleTableChange}
      {...baseProps}
    />
  );
};
export default useAsyncTable;
